package cn.lsh.web.shiro;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.lsh.pojo.Module;
import cn.lsh.pojo.Role;
import cn.lsh.pojo.User;
import cn.lsh.service.UserService;

public class AuthRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;

	//授权	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		// TODO Auto-generated method stub
System.out.println("*********授权*********");
		//获取session中的用户
		User user=(User) principal.fromRealm(this.getClass().getName()).iterator().next();
		List<String> permissions=new ArrayList<String>();
		List<String> roleNames=new ArrayList<String>();
		Set<Role> roles=user.getRoles();//获得用户的角色集合
		if(roles.size()>0){
			for(Role role:roles){
				roleNames.add(role.getRname());
				Set<Module> modules=role.getModules();//获得每个角色所拥有的权限集合
				if(modules.size()>0){
					for(Module module:modules){
						permissions.add(module.getMname());
					}
				}
			}
		}
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		//将权限放入shiro中，前台通过<shiro:hasPermission>判断
		info.addStringPermissions(permissions);
		//将角色放入shiro中，前台通过<shiro:hasRole>判断
		info.addRoles(roleNames);
		return info;
	}

	//认证.登录
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
System.out.println("*************身份认证**********");
		//获取用户输入的token
		UsernamePasswordToken utoken=(UsernamePasswordToken) token;
		String username=utoken.getUsername();
System.out.println(username);
		User user=userService.findUserByUserName(username);
		
		if(user==null){
		   throw new UnknownAccountException();//没找到帐号	
		}
		
		//放入shiro.调用CredentialsMatcher检验密码
		SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user, user.getPassword(),
				this.getClass().getName());
		return info;
	}

}
